import React, { PureComponent, createRef, forwardRef } from 'react'

class HelloWorld extends PureComponent {
  render() {
    return (
      <div>
        <h2>HelloWorld Component</h2>
      </div>
    )
  }

  test() {
    console.log('test')
  }
}

const HelloWorld2 = forwardRef(function (props, ref) {
  return (
    <div>
      <h2 ref={ref}>HelloWorld2 Component</h2>
      <p>hahaha</p>
    </div>
  )
})

export class App extends PureComponent {
  constructor() {
    super()
    this.state = {}

    this.titleRef = createRef()
    this.titleEl = null

    this.hwRef = createRef()
    this.hw2Ref = createRef()
  }

  render() {
    return (
      <div>
        {/* <h2 ref="why">App Page</h2> */}
        {/* <h2 ref={this.titleRef}>App Page</h2> */}
        <h2 ref={(el) => (this.titleEl = el)}>App Page</h2>
        <button onClick={(e) => this.getNativeDOM()}>获取DOM</button>

        <HelloWorld ref={this.hwRef} />
        <button onClick={(e) => this.getComponent()}>获取类组件实例</button>

        <HelloWorld2 ref={this.hw2Ref} />
        <button onClick={(e) => this.getFuncComponent()}>
          获取函数组件实例
        </button>
      </div>
    )
  }

  getNativeDOM() {
    // 1.直接通过DOM操作获取元素的DOM，不推荐：可能其他组件也有h2元素
    // const h2El = document.querySelector('h2')

    // 2.在react元素上绑定一个ref, 不推荐
    // console.log(this.refs.why)

    // 3.提前创建ref对象，createRef(), 将创建出来的对象绑定的元素上
    // console.log(this.titleRef.current)

    // 4.通过绑定事件的回调函数第一个参数是DOM元素进行操作
    console.log(this.titleEl)
  }

  getComponent() {
    // 函数组件没有实例this
    console.log(this.hwRef.current)
    this.hwRef.current.test()
  }

  getFuncComponent() {
    console.log(this.hw2Ref.current)
  }
}

export default App
